package com.book.controller;

import java.io.File;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class InitController {

	private static final Logger logger = Logger.getLogger(InitController.class);

	@RequestMapping(value = "init", method = RequestMethod.GET)
	@ResponseBody
	public void initDb() throws Exception {
		long start = System.currentTimeMillis();
		Properties jdbcProp = new Properties();
		jdbcProp.load(this.getClass().getResourceAsStream("/jdbc.properties"));

		logger.info("正在插入数据......");
		File buildFile = new File(this.getClass().getResource("/init/build-initdb.xml").getFile());
		Project prj = new Project();
		prj.init();
		ProjectHelper helper = ProjectHelper.getProjectHelper();
		helper.parse(prj, buildFile);

		prj.setProperty("driver", jdbcProp.getProperty("jdbc.driverClassName"));
		prj.setProperty("url", jdbcProp.getProperty("jdbc.url"));
		prj.setProperty("username", jdbcProp.getProperty("jdbc.username"));
		prj.setProperty("password", jdbcProp.getProperty("jdbc.password"));

		DefaultLogger buildLogger = new DefaultLogger();
		buildLogger.setErrorPrintStream(System.err);
		buildLogger.setOutputPrintStream(System.out);
		buildLogger.setMessageOutputLevel(Project.MSG_VERBOSE);
		prj.addBuildListener(buildLogger);

		prj.executeTarget(prj.getDefaultTarget());

		logger.info("数据插入已完成,用时：" + (System.currentTimeMillis() - start) / 1000 + "秒.");
	}
}
